package com.googlecode.sere.method

import com.googlecode.sere.util.Logging
import com.googlecode.sere.translation.AcceptedTypes
import com.googlecode.sere.http.{Status, EnclosedEntity, HttpRequest}
import com.googlecode.sere.core.{PostUrlRegistry, InvocationData}

class PostMethod(uri: String, entity: EnclosedEntity, acceptedTypes: AcceptedTypes)
  extends EntityEnclosingMethod(uri, entity, acceptedTypes) with Logging {

  def process(meta: InvocationData) = {
    val ((typeReq, typeRes, action), id) = PostUrlRegistry.matchUrl(uri)
    // Lazy value to avoid parsing when another error (such as a 404) will occur
    lazy val parsedEntity = typeReq.parse(entity)
    // TODO: Pass the user
    val postResponse = action(parsedEntity)
    postResponse match {
      case NewResourceResponse(uri) => UriResponse(Status.Created, uri)
      case NoResponse() => EmptyResponse(Status.NoContent)
      case NoUriResponse(body) => EntityResponse(Status.Ok, typeRes.serialize(acceptedTypes, body))
    }
  }

  def this(request: HttpRequest) =
    this(request.uri, EntityEnclosingMethod.entityFromRequest(request), request.acceptedTypes)
}

object PostMethod {
  def fromRequest(request: HttpRequest) = new PostMethod(request.uri,
    EntityEnclosingMethod.entityFromRequest(request), request.acceptedTypes)
}
